package com.gemcoder.system.service;

import static com.gemcoder.system.datasource.JdbcTemplateUtil.executeSQL;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Service;
import static com.gemcoder.system.service.UserSdkService.sdkOfGetCurrentUserName;
import static com.gemcoder.system.service.UserSdkService.sdkOfGetCurrentUserId;
import com.gemcoder.system.bo.Result;
import static com.gemcoder.system.service.permission.PermissionSdkService.sdkOfgetAllPermissions;
import static com.gemcoder.system.service.permission.PermissionSdkService.sdkOfgetAllMenus;
import java.sql.SQLException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.NumberUtil;
import java.util.Date;

@Service
public class RolemanagementService {

    public Result getRolesByRoleName(Map<String, Object> paramMap) {
        String roleName = paramMap.get("roleName") != null ? String.valueOf(paramMap.get("roleName")) : "";
        Integer current = paramMap.get("current") != null ? Integer.valueOf(String.valueOf(paramMap.get("current"))) : 1;
        Integer pageSize = paramMap.get("pageSize") != null ? Integer.valueOf(String.valueOf(paramMap.get("pageSize"))) : 10;
        StringBuilder sql = new StringBuilder("SELECT id, role_name, role_code, role_description FROM role WHERE 1=1");
        List<Object> params = new ArrayList<>();
        if (roleName != null && !roleName.isEmpty()) {
            sql.append(" AND role_name LIKE ?");
            params.add("%" + roleName + "%");
        }
        sql.append(" LIMIT ?, ?");
        params.add((current - 1) * pageSize);
        params.add(pageSize);
        List<Map<String, Object>> data = executeSQL(sql.toString(), params.toArray());
        StringBuilder countSql = new StringBuilder("SELECT COUNT(*) as total FROM role WHERE 1=1");
        List<Object> countParams = new ArrayList<>();
        if (roleName != null && !roleName.isEmpty()) {
            countSql.append(" AND role_name LIKE ?");
            countParams.add("%" + roleName + "%");
        }
        List<Map<String, Object>> countResult = executeSQL(countSql.toString(), countParams.toArray());
        Integer total = countResult.get(0) != null ? Integer.valueOf(String.valueOf(countResult.get(0).get("total"))) : 0;
        Map<String, Object> result = new HashMap<>();
        result.put("total", total);
        result.put("data", data);
        return new Result(true, "查询成功", result);
    }

    public Result getAllRoles(Map<String, Object> paramMap) {
        Integer current = paramMap.get("current") != null ? Integer.valueOf(String.valueOf(paramMap.get("current"))) : 1;
        Integer pageSize = paramMap.get("pageSize") != null ? Integer.valueOf(String.valueOf(paramMap.get("pageSize"))) : 10;
        StringBuilder sql = new StringBuilder("SELECT id, role_name, role_code, role_description FROM role LIMIT ?, ?");
        List<Object> params = new ArrayList<>();
        params.add((current - 1) * pageSize);
        params.add(pageSize);
        List<Map<String, Object>> data = executeSQL(sql.toString(), params.toArray());
        StringBuilder countSql = new StringBuilder("SELECT COUNT(*) as total FROM role");
        List<Map<String, Object>> countResult = executeSQL(countSql.toString());
        Integer total = countResult.get(0) != null ? Integer.valueOf(String.valueOf(countResult.get(0).get("total"))) : 0;
        Map<String, Object> result = new HashMap<>();
        result.put("total", total);
        result.put("data", data);
        return new Result(true, "查询成功", result);
    }

    public Result getRolesByPage(Map<String, Object> paramMap) {
        Integer current = paramMap.get("current") != null ? Integer.valueOf(String.valueOf(paramMap.get("current"))) : 1;
        Integer pageSize = paramMap.get("pageSize") != null ? Integer.valueOf(String.valueOf(paramMap.get("pageSize"))) : 10;
        StringBuilder sql = new StringBuilder("SELECT id, role_name, role_code, role_description FROM role LIMIT ?, ?");
        List<Object> params = new ArrayList<>();
        params.add((current - 1) * pageSize);
        params.add(pageSize);
        List<Map<String, Object>> data = executeSQL(sql.toString(), params.toArray());
        StringBuilder countSql = new StringBuilder("SELECT COUNT(*) as total FROM role");
        List<Map<String, Object>> countResult = executeSQL(countSql.toString());
        Integer total = countResult.get(0) != null ? Integer.valueOf(String.valueOf(countResult.get(0).get("total"))) : 0;
        Map<String, Object> result = new HashMap<>();
        result.put("total", total);
        result.put("data", data);
        return new Result(true, "查询成功", result);
    }

    public Result showEditModal(Map<String, Object> paramMap) {
        Integer id = paramMap.get("id") != null ? Integer.valueOf(String.valueOf(paramMap.get("id"))) : null;
        if (id == null) {
            return new Result(false, "ID不能为空", null);
        }
        StringBuilder sql = new StringBuilder("SELECT id, role_name, role_code, role_description FROM role WHERE id = ?");
        List<Object> params = new ArrayList<>();
        params.add(id);
        List<Map<String, Object>> data = executeSQL(sql.toString(), params.toArray());
        if (data.isEmpty()) {
            return new Result(false, "未找到对应的角色", null);
        }
        return new Result(true, "查询成功", data.get(0));
    }

    public Result deleteRole(Map<String, Object> paramMap) {
        Integer id = paramMap.get("id") != null ? Integer.valueOf(String.valueOf(paramMap.get("id"))) : null;
        if (id == null) {
            return new Result(false, "ID不能为空", null);
        }
        StringBuilder sql = new StringBuilder("DELETE FROM role WHERE id = ?");
        List<Object> params = new ArrayList<>();
        params.add(id);
        int rows = executeSQL(sql.toString(), params.toArray());
        if (rows > 0) {
            return new Result(true, "删除成功", null);
        } else {
            return new Result(false, "删除失败", null);
        }
    }

    public Result updateRolePermissions(Map<String, Object> paramMap) {
        Integer roleId = paramMap.get("roleId") != null ? Integer.valueOf(String.valueOf(paramMap.get("roleId"))) : null;
        List<Integer> permissionIds = paramMap.get("permissionIds") != null ? (List<Integer>) paramMap.get("permissionIds") : null;
        if (roleId == null || permissionIds == null) {
            return new Result(false, "角色ID和权限ID不能为空", null);
        }
        // 删除旧的权限
        StringBuilder deleteSql = new StringBuilder("DELETE FROM role_permission WHERE role_id = ?");
        List<Object> deleteParams = new ArrayList<>();
        deleteParams.add(roleId);
        executeSQL(deleteSql.toString(), deleteParams.toArray());
        // 插入新的权限
        StringBuilder insertSql = new StringBuilder("INSERT INTO role_permission (role_id, permission_id, create_username, create_time) VALUES (?, ?, ?, ?)");
        String currentUserName = sdkOfGetCurrentUserName();
        Date currentTime = new Date();
        for (Integer permissionId : permissionIds) {
            List<Object> insertParams = new ArrayList<>();
            insertParams.add(roleId);
            insertParams.add(permissionId);
            insertParams.add(currentUserName);
            insertParams.add(currentTime);
            executeSQL(insertSql.toString(), insertParams.toArray());
        }
        return new Result(true, "更新成功", null);
    }

    public Result addRole(Map<String, Object> paramMap) {
        // 获取当前登录用户的名称
        String currentUserName = sdkOfGetCurrentUserName();
        // 获取参数
        String roleName = paramMap.get("RoleName1value1") != null ? String.valueOf(paramMap.get("RoleName1value1")) : null;
        String roleCode = paramMap.get("RoleCodevalue1") != null ? String.valueOf(paramMap.get("RoleCodevalue1")) : null;
        String roleDescription = paramMap.get("Descriptionvalue1") != null ? String.valueOf(paramMap.get("Descriptionvalue1")) : null;
        // 构建插入SQL
        StringBuilder insertSql = new StringBuilder("INSERT INTO role (role_name, role_code, role_description, create_time, update_time, create_username, update_username) VALUES (?, ?, ?, NOW(), NOW(), ?, ?)");
        List<Object> params = new ArrayList<>();
        params.add(roleName);
        params.add(roleCode);
        params.add(roleDescription);
        params.add(currentUserName);
        params.add(currentUserName);
        // 执行插入操作
        int insertRows = executeSQL(insertSql.toString(), params.toArray());
        // 返回结果
        if (insertRows > 0) {
            return new Result(true, "新增角色成功", null);
        } else {
            return new Result(false, "新增角色失败", null);
        }
    }

    public Result getAllRoles0VT(Map<String, Object> paramMap) {
        // 获取分页参数
        Integer current = paramMap.get("current") != null ? Integer.valueOf(String.valueOf(paramMap.get("current"))) : 1;
        Integer pageSize = paramMap.get("pageSize") != null ? Integer.valueOf(String.valueOf(paramMap.get("pageSize"))) : 10;
        // 构建查询SQL
        StringBuilder sql = new StringBuilder("SELECT id, role_name, role_code, role_description FROM role LIMIT ?, ?");
        List<Object> params = new ArrayList<>();
        params.add((current - 1) * pageSize);
        params.add(pageSize);
        // 执行查询操作
        List<Map<String, Object>> data = executeSQL(sql.toString(), params.toArray());
        // 构建统计总数的SQL
        String countSql = "SELECT COUNT(*) AS total FROM role";
        List<Map<String, Object>> countResult = executeSQL(countSql);
        int total = countResult.get(0).get("total") != null ? Integer.valueOf(String.valueOf(countResult.get(0).get("total"))) : 0;
        // 返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("total", total);
        result.put("data", data);
        return new Result(true, "查询成功", result);
    }

    public Result getAllPermissions(Map<String, Object> paramMap) {
        // 获取所有权限项
        List<Map<String, Object>> allPermissions = sdkOfgetAllPermissions();
        return new Result(true, "获取所有权限项成功", allPermissions);
    }

    public Result getRolePermissions(Map<String, Object> paramMap) {
        // 从参数中获取角色ID
        Integer roleId = paramMap.get("roleId") != null ? Integer.valueOf(String.valueOf(paramMap.get("roleId"))) : null;
        if (roleId == null) {
            return new Result(false, "角色ID不能为空", null);
        }
        // 查询角色拥有的权限项
        StringBuilder sql = new StringBuilder("SELECT p.id, p.permission_name, p.permission_code, p.permission_description ");
        sql.append("FROM permission p ");
        sql.append("JOIN role_permission rp ON p.id = rp.permission_id ");
        sql.append("WHERE rp.role_id = ?");
        List<Map<String, Object>> rolePermissions = executeSQL(sql.toString(), roleId);
        return new Result(true, "获取角色权限项成功", rolePermissions);
    }
}
